<template>
  <div>
     <div class="sea_form">
        <searchForm @sendQuery="getList" :formData="formData"></searchForm>
     </div>
     <div class="btnlist" style="margin:10px 0">
      <el-button type="primary" @click="open">新增</el-button>
      <el-button type="success">修改</el-button>
      <el-button type="danger">删除</el-button>
      <el-button type="warning" @click="uploadFlag=true">导入</el-button>
      <el-button type="primary" @click="exportData">导出</el-button>
     </div>
     <div>
      <el-table :data="userList">
        <el-table-column label="用户编号" type="index"></el-table-column>
        <el-table-column label="用户名称" prop="userName"></el-table-column>
        <el-table-column label="用户昵称" prop="nickName"></el-table-column>
        <!-- 深层对象 -->
        <el-table-column label="部门" prop="dept.deptName"></el-table-column>
        <el-table-column label="手机号" prop="phonenumber"></el-table-column>
        <el-table-column label="状态" >
          <template #default="{row}">
            <div>
               {{row.status=='1'?'启用':'禁用'}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="操作">
          <template #default="{row}">
            <div>
              <el-link type="primary" @click="toEdit(row.userId)">修改</el-link>
              <el-link type="primary" style="margin:0 10px;" @click="toDel(row.userId)">删除</el-link>
              <el-link type="primary">更多</el-link>
            </div>
          </template>
        </el-table-column>
        
      </el-table>
      <Pagination v-model:page="queryData.pageNum" 
      v-model:limit="queryData.pageSize"  :total="total" 
      @pagination="getList"></Pagination>
     </div> 
    <el-dialog title="添加用户" v-model="userFlag" width="50%">
        <el-form label-width="100px" :model="formObj" :rules="rules"
        ref="userForm">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="nickName" label="用户昵称">
                <el-input v-model="formObj.nickName"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="归属部门">
                <el-tree-select :data="deptList"
                :props="{label:'deptName',value:'deptId'}"
                node-key="deptId"
                v-model="formObj.deptId">
                <template #default="{ node, data }">
                    {{data.deptName}}
                    <span v-if="data.children.length!=0"> ({{data.children.length}})</span>
                   
                 </template>
                </el-tree-select>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号">
                <el-input v-model="formObj.phonenumber"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱">
                <el-input v-model="formObj.email"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="userName" label="用户名称">
                <el-input v-model="formObj.userName"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="password" label="用户密码">
                <el-input v-model="formObj.password" show-password  type="password"></el-input>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别">
               <el-select v-model="formObj.sex">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
                <el-option label="未知" value="2"></el-option>
               </el-select>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="formObj.status">
                  <el-radio value="0">正常</el-radio>
                  <el-radio value="1">禁用</el-radio>
                </el-radio-group>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="岗位">
                <el-select multiple v-model='formObj.postIds'>
                   <el-option v-for="item in postList" :label="item.postName" :value="item.postId"></el-option>
                </el-select>
               </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="角色">
                <el-select v-model="formObj.roleIds" multiple>
                  <el-option  v-for="item in roleList" :label="item.roleName" :value="item.roleId"></el-option>
                </el-select>
               </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                 <el-input v-model="formObj.remark" type="textarea"></el-input>
               </el-form-item>
            </el-col>
          </el-row>
          
   
        </el-form>
          <template #footer>
            <el-button @click="toSave" type="primary">确定</el-button>
            <el-button @click="userFlag=false">取消</el-button>
          </template>
    </el-dialog>
    <!-- 导入弹出层 -->
     <el-dialog v-model="uploadFlag" widht="70%" title="导入用户">
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"

        :on-change="getFile"
        multiple
      >
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text">
      Drop file here or <em>选择上传</em>
    </div>
    <template #tip>
      <div class="el-upload__tip">
        jpg/png files with a size less than 500kb
        <div>
          <el-link type="primary" @click="toDown">下载模版</el-link>
        </div>
      </div>
    </template>
  </el-upload>
    <template #footer>
      <el-button type="primary" @click="toUpload">确定</el-button>
      <el-button type="primary">取消</el-button>
    </template>
     </el-dialog>
  </div>
</template>
<script setup>
  import seaFormHook from './listHook.js'
import Pagination from '@/components/Pagination/index.vue';
import {listUser,addUser,getUser,updateUser,delUser,importTemplate,importDataUser} from '@/api/system/user.js'
  import {listDept} from '@/api/system/dept'
  import {listPost} from '@/api/system/post'
  import {listRole} from '@/api/system/role'
  import {handleTree} from '@/utils/ruoyi'
  import { ElMessage } from 'element-plus';
import {ref,reactive,watch} from 'vue'
import fileSaver from 'file-saver'
import * as XLSX from 'xlsx'
  const {formData}=seaFormHook()
  console.log(formData,"---------")
  let queryData=reactive({
    pageNum:1,
    pageSize:3
  })
  let userList=ref([])
  let total=ref(0)
  let getList=async (serForm)=>{ 
     let query={...serForm,...queryData}
      let res=await listUser(query)
      console.log(res,"用户列表")
      userList.value=res.rows;
      total.value=res.total
  }
  getList();
  let userFlag=ref(false)
  let deptList=ref([]);
  let postList=ref([]);
  let roleList=ref([]);
  // 添加弹出层
   let getAddInfo=async ()=>{
      let depts=await listDept()
      console.log(depts,"部门列表")
      deptList.value=handleTree(depts.data,'deptId');
      let posts=await listPost()
      console.log(posts,"岗位列表")
      postList.value=posts.rows;
     let roles=await listRole()
      console.log(roles,"角色列表")
      roleList.value=roles.rows;
   }
   let open=()=>{
    userFlag.value=true;
    getAddInfo();
   }
  //  表单的 v-model
   let formObj=reactive({
    deptId:'', //部门id
    sex:'',  //性别
    status:'', //状态
    userName:'', //用户名称
    password:'', //用户密码
    phonenumber:'', //  手机号
    email:'', //邮箱
    remark:'',//备注
    postIds:[],//岗位ids
    roleIds:[],//  角色ids
    nickName:""
   })
  // 表单的验证
  let rules={ 
    userName:{
      required:true,
      message:"请输入用户名称",
      trigger:"blur"
    },
    password:{
      required:true,
      message:"请输入用户密码",
      trigger:"blur"
    },
    nickName:{
      required:true,
      message:"请输入昵称",
      trigger:"blur"
    }
  }
  let userForm=ref(null)
  // 添加接口
  let toSave=async ()=>{
    userForm.value.validate(async (vali)=>{
      if(formObj.userId){
         let editRes=await updateUser(formObj)
         console.log(editRes,"修改用户")
         ElMessage.success("修改成功")
      }else{
        let res=await addUser(formObj)
        console.log(res,"添加用户")
        ElMessage.success("添加成功")
      }
   
        
        getList();
        userFlag.value=false

    })
  }

  // 编辑回显
  let toEdit=async (userId)=>{
      getAddInfo();
      let res=await getUser(userId);
      console.log(res,"回显示数据")
      userFlag.value=true;
      formObj.deptId=res.data.deptId;
      formObj.sex=res.data.sex;
      formObj.status=res.data.status;
      formObj.userName=res.data.userName;
      formObj.password=res.data.password;
      formObj.phonenumber=res.data.phonenumber;
      formObj.email=res.data.email;
      formObj.remark=res.data.remark;
   
      formObj.remark=res.data.remark;//  角色ids
      formObj.nickName=res.data.nickName;
      formObj.postIds=res.postIds;// 岗位ids
      formObj.roleIds=res.roleIds;//  角色ids
      formObj.userId=res.data.userId;
  }
  
  watch(userFlag,(newVal)=>{
    if(!newVal){
        formObj=reactive({
          deptId:'', //部门id
          sex:'',  //性别
          status:'', //状态
          userName:'', //用户名称
          password:'', //用户密码
          phonenumber:'', //  手机号
          email:'', //邮箱
          remark:'',//备注
          postIds:[],//岗位ids
          roleIds:[],//  角色ids
          nickName:""
        })
    }
  })
  // 删除接口
  let toDel=async (userId)=>{
    let res=await delUser(userId)
    ElMessage.success("删除成功")
    getList();
  }

  // 导出excel
  let exportData=()=>{
     let book=XLSX.utils.book_new(); //创建文件
    // 创建表
     let sheet=XLSX.utils.json_to_sheet(userList.value);
    //  const sheet = XLSX.utils.aoa_to_sheet(userList.value);
    //  给表格的所有单元格 加上实线
    // 难点： 产品要求： 1. 表头需要加上背景色 2. 表格需要加上边框
    // 加上很多样式，需要使用到样式表、
    //  给表头加上背景色
     // 设置表头背景色（例如，使用黄色背景）
   
     //  给表格 加上边框
    //  将表格添加到文件中
    XLSX.utils.book_append_sheet(book,sheet,"用户列表")
    // 下载文件
    XLSX.writeFile(book,"用户列表.xlsx")
  }
  let uploadFlag=ref(false);
// 下载模版接口
 let toDown=async ( )=>{
     let res=await importTemplate();
     console.log(res,"------文件--------------")
    //  保存文件插件
     fileSaver.saveAs(res,'用户模板.xlsx')
 }
 let myfile=ref('')
//  change事件获取选择的文件


 let getFile=(file)=>{

  myfile.value=file.raw;
  // let reader= new FileReader();

  // reader.readAsDataURL(file.raw);
  // reader.onload=(data)=>{
  //   myfile.value=data.target.result; //保存文件流
  //   console.log(reader.result,"文件")
  // }
  
 
 }
//  导入接口
let toUpload=async ()=>{
  let formdata=new FormData();
  formdata.append("file",myfile.value);
  let res=await importDataUser(formdata)
  console.log(res,"导入数据")
  getList();
  uploadFlag.value=false;
}
</script>
